package com.chidopi.market.bookstore.actions;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.chidopi.cdf.struts1actions.CdfDispatchAction;
import com.chidopi.cdf.util.ModelContextFactory;
import com.chidopi.market.bookstore.domain.BookZipBackup;
import com.chidopi.market.bookstore.service.IBookZipBackupService;
import com.chidopi.market.bookstore.service.IResourceService;
import com.chidopi.market.util.FileHelper;

public class BookZipBackupAction extends CdfDispatchAction{
	
	private String RES_PATH = "";
	
	private static Logger logger = LoggerFactory.getLogger(BookZipBackupAction.class);
	
	private IBookZipBackupService baseService;
	
	private IResourceService resourceService;
		
	public BookZipBackupAction(){
		this("");
	}
	
	public BookZipBackupAction(String entryURL) {
		this.entryURL = entryURL;
		try {
			this.baseService = (IBookZipBackupService)
				ModelContextFactory.get("backupService", IBookZipBackupService.class);
		} catch (Exception e) {
			this.baseService = null;
			logger.warn("initial IBookZipBackupService", e);
		}
		
		try{
			this.resourceService = (IResourceService)
			    ModelContextFactory.get("resourceService", IResourceService.class);
			logger.debug("Path: " + resourceService.getBookCityResPath());
			this.RES_PATH = resourceService.getBookCityResPath();
		}catch(Exception e){
			this.resourceService = null;
			logger.warn("initial IResourceService", e);
		}
	}
	
	public ActionForward init(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		DynaBean dynaForm = (DynaBean) form;
		dynaForm.set("vo", null);
		dynaForm.set("op", null);
        // bookitems list
		List<Map<String, Object>> list  = baseService.getBookItemsList();
		dynaForm.set("bookitems", list);
		logger.debug("BookItem list: " + list);
		return mapping.findForward("success");
	}
	
	public ActionForward back(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		return mapping.findForward("success");
	}
	

	// 分類查詢
	//private static final String[] conditions = {"BOOK_ID"};
	public ActionForward query(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (null == this.baseService) return mapping.findForward("error");
        String id = request.getParameter("id");
        String condition = "";
        ArrayList<String> args = new ArrayList<String>();
        if(id != null && id.trim().length() > 0){
        	condition = " BOOK_ID = ?";
        	args.add(id);
        }        
		List<BookZipBackup> list = this.baseService.getBackupList(condition, args.toArray());
		logger.debug("size=" + list.size());
		JSONArray json = JSONArray.fromObject(list);
		PrintWriter out=response.getWriter();
		logger.debug(json.toString());
        out.println(json);
        out.flush();
		return null;
	}
	
	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String zipfile = request.getParameter("zipfile");
		logger.debug("zipfile" + zipfile);
		BookZipBackup t = this.baseService.findByZipfile(zipfile);
		if (null == t) {
			logger.warn("BookItems[zipfile={}] is deleted!!", zipfile);
			return mapping.findForward("err");
		}
		DynaBean dynaForm = (DynaBean) form;
		dynaForm.set("op", "delete");
		dynaForm.set("vo", t);
		
		return mapping.findForward("success");
	}

	public ActionForward remove(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)throws Exception {
		
		BookZipBackup t = new BookZipBackup();
		DynaBean dynaForm = (DynaBean) form;
		try {			
			PropertyUtils.copyProperties(t, dynaForm.get("vo"));
			logger.debug(t.getCreate_time());
		} catch (Exception e) {
			logger.warn("PropertyUtils", e);
			return mapping.findForward("err");
		}
		
		int ret = -1;		
		ret = this.baseService.deleteBackup(t);				

		if (ret > -1) {
			// delete file
			String path = RES_PATH + t.getZipfile();
			logger.debug("delete file: " + path);
			FileHelper.deleteFile(path);
			request.setAttribute("entryURL", entryURL);
			return mapping.findForward("success");
		}else {
			return mapping.findForward("err");
		}
	}

	public ActionForward backupDownload(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String zipfile = request.getParameter("zipfile");
		if(zipfile != null && zipfile.length() > 0){
			BookZipBackup backup = this.baseService.findByZipfile(zipfile);
			if(backup != null && backup.getZipfile() != null){
				String path = RES_PATH + backup.getZipfile();
				FileHelper.downloadFile(response, path, backup.getZipfilename());
			}
			
		}
		return null;
	}
}
